#!/bin/bash
#----------------------------------------------------------------------------
# Purpose:
# Copyright Huawei Technologies Co., Ltd. 2010-2018. All rights reserved.
#----------------------------------------------------------------------------

#set -e

create_file_sha()
{
	local files="$1"

	for file in ${files[@]};
		do
			echo "check_file_sha $($security_ck_cmd $file)" >> check_sha.sh
                        if [ $? -ne 0 ]; then
				echo "gen file security check fail"
				exit 1
                        fi
		done
}

echo 'exec gen security check start!'
subdirs_str="$2"
OLD_IFS="$IFS"
IFS=","
subdirs=($subdirs_str)
IFS="$OLD_IFS"

file_list=""
cd "$1"
for subdir in ${subdirs[@]};
	do
		echo "subdir is: $subdir"
		file_list="$file_list $(find $subdir -type f -print)"
        done
case "$3" in
    sha256)
	security_ck_cmd=sha256sum
	;;
    sha384)
	security_ck_cmd=sha384sum
	;;
esac

if [ -f "check_sha.sh" ];then
	rm -rf check_sha.sh
fi

echo '#!/bin/bash'                            >  check_sha.sh
echo 'check_file_sha()'                       >> check_sha.sh
echo '{'                                      >> check_sha.sh
echo '    local sha_value=$1'                 >> check_sha.sh
echo '    local file=$2'                      >> check_sha.sh
echo '    str=$('"$security_ck_cmd"' $file)'    >> check_sha.sh
echo '    shastr=${str%% *}'                  >> check_sha.sh
echo '    if [ $sha_value != $shastr ]; then' >> check_sha.sh
echo '        echo "check files fail, sha vaule is not correct!"' >> check_sha.sh
echo '        exit 1'                         >> check_sha.sh
echo '    fi'                                 >> check_sha.sh
echo '}'                                      >> check_sha.sh

create_file_sha "${file_list[@]}"

echo 'echo "files check pass!"'  >> check_sha.sh
echo 'exit 0'                    >> check_sha.sh
chmod 550 check_sha.sh

./check_sha.sh
if [ $? -ne 0 ]; then
	echo "exec file security check fail"
	exit 1
fi

